var criteria = 
{ Name: "Products", Level2: [
    { Name: "Product Involvement", Level3: [
		{ Name: "Small Arms", Level4: [{OldName:"Small Arms Civilian customers-Standard Analysis", Name: "Small Arms Civilian customers (Assault weapons)-Standard Analysis",OldCategory:"Civilian customers",NewCategory:"Civilian customers (Assault weapons)", CriteriaEntityField: "FA FA1 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false }] },
		{ Name: "Small Arms", Level4: [{ OldName: "Small Arms Civilian customers-Category of Involvement", Name: "Small Arms Civilian customers (Assault weapons)-Category of Involvement",OldCategory:"Civilian customers",NewCategory:"Civilian customers (Assault weapons)", CriteriaEntityField: "FA FA1 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Civilian customers-Level of Involvement",  Name: "Small Arms Civilian customers (Assault weapons)-Level of Involvement",OldCategory:"Civilian customers",NewCategory:"Civilian customers (Assault weapons)", CriteriaEntityField: "FA FA1 Level of Involvement", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Significant ownership (Civilian customers)-Range Ownership",  Name: "Small Arms Significant ownership (Civilian customers - assault weapons)-Range Ownership",OldCategory:"Significant ownership (Civilian customers)",NewCategory:"Significant ownership (Civilian customers - assault weapons)", CriteriaEntityField: "FA FA2 Range Ownership", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Significant ownership (Civilian customers)-Standard Analysis",  Name: "Small Arms Significant ownership (Civilian customers - assault weapons)-Standard Analysis",OldCategory:"Significant ownership (Civilian customers)",NewCategory:"Significant ownership (Civilian customers - assault weapons)", CriteriaEntityField: "FA FA2 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Significant ownership (Civilian customers)-Category of Involvement",  Name: "Small Arms Significant ownership (Civilian customers - assault weapons)-Category of Involvement",OldCategory:"Significant ownership (Civilian customers)",NewCategory:"Significant ownership (Civilian customers - assault weapons)", CriteriaEntityField: "FA FA2 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Retail/distribution-Standard Analysis",  Name: "Small Arms Retail/distribution (Assault weapons)-Standard Analysis",OldCategory:"Retail/distribution",NewCategory:"Retail/distribution (Assault weapons)", CriteriaEntityField: "FA FA7 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Retail/distribution-Category of Involvement",  Name: "Small Arms Retail/distribution (Assault weapons)-Category of Involvement",OldCategory:"Retail/distribution",NewCategory:"Retail/distribution (Assault weapons)", CriteriaEntityField: "FA FA7 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Retail/distribution-Level of Involvement",  Name: "Small Arms Retail/distribution (Assault weapons)-Level of Involvement",OldCategory:"Retail/distribution",NewCategory:"Retail/distribution (Assault weapons)", CriteriaEntityField: "FA FA7 Level of Involvement", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Significant ownership (Retail/distribution)-Category of Involvement",  Name: "Small Arms Significant ownership (Retail/distribution - assault weapons)-Category of Involvement",OldCategory:"Significant ownership (Retail/distribution)",NewCategory:"Significant ownership (Retail/distribution - assault weapons)", CriteriaEntityField: "FA FA8 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Significant ownership (Retail/distribution)-Standard Analysis",  Name: "Small Arms Significant ownership (Retail/distribution - assault weapons)-Standard Analysis",OldCategory:"Significant ownership (Retail/distribution)",NewCategory:"Significant ownership (Retail/distribution - assault weapons)", CriteriaEntityField: "FA FA8 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"Small Arms Significant ownership (Retail/distribution)-Range Ownership",  Name: "Small Arms Significant ownership (Retail/distribution - assault weapons)-Range Ownership",OldCategory:"Significant ownership (Retail/distribution)",NewCategory:"Significant ownership (Retail/distribution - assault weapons)", CriteriaEntityField: "FA FA8 Range Ownership", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Retail/distribution (Non-assault weapons)-Standard Analysis", CriteriaEntityField: "FA FA9 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Retail/distribution (Non-assault weapons)-Category of Involvement", CriteriaEntityField: "FA FA9 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Retail/distribution (Non-assault weapons)-Level of Involvement", CriteriaEntityField: "FA FA9 Level of Involvement", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Significant ownership (Retail/distribution - Non-assault weapons)-Category of Involvement", CriteriaEntityField: "FA FA10 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Significant ownership (Retail/distribution - Non-assault weapons)-Standard Analysis", CriteriaEntityField: "FA FA10 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Significant ownership (Retail/distribution - Non-assault weapons)-Range Ownership", CriteriaEntityField: "FA FA10 Range Ownership", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"", Name: "Small Arms Civilian customers (Non-assault weapons)-Standard Analysis", CriteriaEntityField: "FA FA11 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false }] },
		{ Name: "Small Arms", Level4: [{ OldName:"", Name: "Small Arms Civilian customers (Non-assault weapons)-Category of Involvement", CriteriaEntityField: "FA FA11 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Civilian customers (Non-assault weapons)-Level of Involvement", CriteriaEntityField: "FA FA11 Level of Involvement", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:false}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Significant ownership (Civilian customers - Non-assault weapons)-Category of Involvement", CriteriaEntityField: "FA FA12 Category of Involvement", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Significant ownership (Civilian customers - Non-assault weapons)-Standard Analysis", CriteriaEntityField: "FA FA12 Standard Analysis", IsScreenable: false, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
		{ Name: "Small Arms", Level4: [{ OldName:"",  Name: "Small Arms Significant ownership (Civilian customers - Non-assault weapons)-Range Ownership", CriteriaEntityField: "FA FA12 Range Ownership", IsScreenable: true, CriteriaType: 4, HasFullRangeChart:false, HasOwnValue:true}] },
    ]}
]};

function uuid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }
    return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
}

function HexToBase64(hex) {
    var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var base64 = "";
    var group;
    for (var i = 0; i < 30; i += 6) {
        group = parseInt(hex.substr(i, 6), 16);
        base64 += base64Digits[(group >> 18) & 0x3f];
        base64 += base64Digits[(group >> 12) & 0x3f];
        base64 += base64Digits[(group >> 6) & 0x3f];
        base64 += base64Digits[group & 0x3f];
    }
    group = parseInt(hex.substr(30, 2), 16);
    base64 += base64Digits[(group >> 2) & 0x3f];
    base64 += base64Digits[(group << 4) & 0x3f];
    base64 += "==";
    return base64;
}

function NUUID(uuid) {
    var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
    var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
    var b = hex.substr(10, 2) + hex.substr(8, 2);
    var c = hex.substr(14, 2) + hex.substr(12, 2);
    var d = hex.substr(16, 16);
    hex = a + b + c + d;
    var base64 = HexToBase64(hex);
    return new BinData(3, base64);
}

function processLevel1(criteria) {
    if (!db.CriteriaLevel1.findOne({ Name: criteria.Name })) {
        db.CriteriaLevel1.insert({
            _id: NUUID(uuid()),
            Name: criteria.Name,
            ShortName: 'Products',
            Order: NumberInt(30)
        });
    }

    var criteriaLevel1Id = db.CriteriaLevel1.findOne({ Name: criteria.Name })._id;

    criteria.Level2.forEach(function (criteria, index) {
        processLevel2(criteriaLevel1Id, criteria, index);
    });
}

function processLevel2(criteriaLevel1Id, criteria, index) {
    if (!db.CriteriaLevel2.findOne({ Name: criteria.Name })) {
        db.CriteriaLevel2.insert({
            _id: NUUID(uuid()),
            CriteriaLevel1Id: criteriaLevel1Id,
            UniverseFeature: NumberInt(9),
            Name: criteria.Name,
            ShortName: 'PI',
            Order: NumberInt(1)
        });
    }

    var criteriaLevel2Id = db.CriteriaLevel2.findOne({ Name: criteria.Name })._id;
    var length = criteria.Level3.length;

    criteria.Level3.forEach(function (criteria, index) {
        processLevel3(criteriaLevel2Id, criteria, index+1);
    });
}

function processLevel3(criteriaLevel2Id, criteria, index) {
    if (!db.CriteriaLevel3.findOne({ Name: criteria.Name, CriteriaLevel2Id: criteriaLevel2Id })) 
    {
		var orderCompanyName = db.CriteriaLevel3.findOne({Name:"Military Contracting"},{CriteriaLevel2Id:criteriaLevel2Id}).Order;
		
        db.CriteriaLevel3.insert({
            _id: NUUID(uuid()),
            Name: criteria.Name,
            ShortName: "",
            Order: orderCompanyName+1,
            CriteriaLevel2Id: criteriaLevel2Id,
            Category: "None",
			isActiveCategory:true
        });
    }

    var criteriaLevel3Id = db.CriteriaLevel3.findOne({ Name: criteria.Name, CriteriaLevel2Id: criteriaLevel2Id })._id;
    
    criteria.Level4.forEach(function (criteria) {
        processLevel4(criteriaLevel2Id, criteriaLevel3Id, criteria, index);
    });
}

function processLevel4(criteriaLevel2Id, criteriaLevel3Id, criteria, index) {
	if(criteria.OldName == ""){
		if (!db.TemplateCriteria.findOne({ Name: criteria.Name, CriteriaLevel2Id: criteriaLevel2Id })) {
			db.TemplateCriteria.insert({
				_id: NUUID(uuid()),
				Name: criteria.Name,
				CriteriaEntity:null,
				CriteriaEntityField: criteria.CriteriaEntityField,
				CriteriaType: NumberInt(criteria.CriteriaType),
				CriteriaLevel2Id: criteriaLevel2Id,
				CriteriaLevel3Id: criteriaLevel3Id,
				IsScreenable: criteria.IsScreenable,
				ResearchProducts: ["ProductInvolvement"],
				HasFullRangeChart: criteria.HasFullRangeChart==false? false : true,
				HasOwnValue: criteria.HasOwnValue==false? false : true
			});
		}
	}
	else
	{
		if (!db.TemplateCriteria.findOne({
			$and : [
					{ $or : [ { Name : criteria.OldName }, { Name : criteria.Name } ] },
					{ CriteriaLevel2Id: criteriaLevel2Id }
				]
		})) {
			db.TemplateCriteria.insert({
				_id: NUUID(uuid()),
				Name: criteria.Name,
				CriteriaEntity:null,
				CriteriaEntityField: criteria.CriteriaEntityField,
				CriteriaType: NumberInt(criteria.CriteriaType),
				CriteriaLevel2Id: criteriaLevel2Id,
				CriteriaLevel3Id: criteriaLevel3Id,
				IsScreenable: criteria.IsScreenable,
				ResearchProducts: ["ProductInvolvement"],
				HasFullRangeChart: criteria.HasFullRangeChart==false? false : true,
				HasOwnValue: criteria.HasOwnValue==false? false : true
			});
		}
		else
		{
			db.TemplateCriteria.update({Name: criteria.OldName, CriteriaLevel2Id: criteriaLevel2Id},
								{$set:{Name: criteria.Name}},{multi:false}
			);
		}

		var filterCriteria = db.FilterCriteria.find({Name: criteria.OldName, CriteriaLevel2Id: criteriaLevel2Id, CriteriaLevel3Id: criteriaLevel3Id});
		
			filterCriteria.forEach(function(obj)
			{
				var selectedvalue = obj.SelectedValue;
				var selectedvalueinformation = obj.SelectedValueInformation;
				
				if(selectedvalue != null){
					var newselectedvalue = selectedvalue.replace("\"CategoryOfInvolvement\":\""+criteria.OldCategory,"\"\CategoryOfInvolvement\":\""+criteria.NewCategory);
					newselectedvalue = newselectedvalue.replace("\"Name\":\""+criteria.OldName,"\"\Name\":\""+criteria.Name);
					}
					
					print(selectedvalueinformation);
					var newselectedvalueinformation = selectedvalueinformation.replace(criteria.OldCategory,criteria.NewCategory);
					
					db.FilterCriteria.update({_id:obj._id},
										{$set:{Name: criteria.Name, SelectedValue:selectedvalue!=null? newselectedvalue:null, SelectedValueInformation:newselectedvalueinformation}},{multi:false}
					);
				
			});		
	}
}
		//replace Speciality with Specialty
		
		db.getCollection('CriteriaLevel3').find({Name:/Speciality/}).forEach(function(e,i) {
			var oldname = e.Name;
			e.Name=e.Name.replace("Speciality","Specialty");
			  db.getCollection('CriteriaLevel3').update(
				{Name:oldname}, 
				{ "$set": { Name: e.Name } }
			);
		});

		db.getCollection('TemplateCriteria').find({Name:/Speciality/}).forEach(function(e,i) {
			var oldname = e.Name;
			e.Name=e.Name.replace("Speciality","Specialty");
			  db.getCollection('TemplateCriteria').update(
				{Name:oldname}, 
				{ "$set": { Name: e.Name } },{multi:true}
			);
		});

		db.getCollection('FilterCriteria').find({Name:/Speciality/}).forEach(function(e,i) {
			var oldname = e.Name;
			var olsdelvalueinfo = e.SelectedValueInformation;
			e.Name=e.Name.replace("Speciality","Specialty");
			e.SelectedValueInformation= e.SelectedValueInformation.replace("Speciality","Specialty");
			  db.getCollection('FilterCriteria').update(
				{Name:oldname, SelectedValueInformation: olsdelvalueinfo}, 
				{ "$set": { Name: e.Name , SelectedValueInformation: e.SelectedValueInformation} },{multi:true}
			);
		});

		//rename non-assault in Small Arms to Non-assault
		
		db.getCollection('TemplateCriteria').find({Name:/non-assault/}).forEach(function(e,i) {
			var oldname = e.Name;
			e.Name=e.Name.replace("non-assault","Non-assault");
			  db.getCollection('TemplateCriteria').update(
				{Name:oldname}, 
				{ "$set": { Name: e.Name } },{multi:true}
			);
		});
                
		db.getCollection('FilterCriteria').find({Name:/non-assault/}).forEach(function(e,i) {
			var oldname = e.Name;
			var olsdelvalueinfo = e.SelectedValueInformation;
			e.Name=e.Name.replace("non-assault","Non-assault");
			e.SelectedValueInformation= e.SelectedValueInformation.replace("non-assault","Non-assault");
			  db.getCollection('FilterCriteria').update(
				{Name:oldname, SelectedValueInformation: olsdelvalueinfo}, 
				{ "$set": { Name: e.Name , SelectedValueInformation: e.SelectedValueInformation} },{multi:true}
			);
		});


processLevel1(criteria);    